﻿using B.S.BaseData.Infrastructure.Interfaces;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace B.S.BaseData.Infrastructure.Implements
{
    public class BaseRepository<T>:IBaseRepository<T> where T : class
    {
        BaseDbContext db;
        ILogger<BaseRepository<T>> logger;

        public BaseRepository(BaseDbContext db,
        ILogger<BaseRepository<T>> logger)
        {
            this.db = db;
            this.logger = logger;
        }

        public async Task<int> AddAsync(T entity)
        {
            try
            {
                await db.Set<T>().AddAsync(entity);
                return await db.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                logger.LogError("添加出错" + ex.Message);
                throw;
            }
        }

        public async Task<int> DelAsync(T entity)
        {
            try
            {
                db.Set<T>().Remove(entity);
                return await db.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                logger.LogError("删除出错" + ex.Message);
                throw;
            }
        }

        public async Task<T> GetAsync(Expression<Func<T, bool>> expression)
        {
            try
            {
                return await db.Set<T>().Where(expression).FirstOrDefaultAsync();
            }
            catch (Exception ex)
            {
                logger.LogError("单值查询出错" + ex.Message);
                throw;
            }
        }

        public IQueryable<T> Query(Expression<Func<T, bool>> expression)
        {
            try
            {
                return db.Set<T>().Where(expression).AsQueryable();
            }
            catch (Exception ex)
            {
                logger.LogError("列表查询出错" + ex.Message);
                throw;
            }
        }

        public async Task<int> UpdateAsync(T entity)
        {
            try
            {
                db.Set<T>().Update(entity);
                return await db.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                logger.LogError("修改出错" + ex.Message);
                throw;
            }
        }
    }
}
